// src/api/http.js
// 统一的 axios 实例与 POST 助手（Vue 3 / Vite 项目，JS 版）
import axios from 'axios';

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 可选：从本地存储里注入 token（如无可删）
http.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

http.interceptors.response.use(
  (res) => res.data, // 服务端统一响应结构 { code, message, data, timestamp }
  (error) => {
    const msg = error?.response?.data?.message || error.message || 'Network Error';
    const status = error?.response?.status;
    const err = new Error(msg);
    err.status = status;
    err.raw = error?.response?.data;
    throw err;
  }
);

/** 直接发 POST，返回服务端统一响应结构 */
export function post(url, body = {}) {
  return http.post(url, body);
}

/** 发 POST 并要求 code === 200，返回 data 字段；否则抛错（message/原始响应在 err.response） */
export async function postOk(url, body = {}) {
  const res = await post(url, body);
  if (res?.code !== 200) {
    const err = new Error(res?.message || 'Request failed');
    err.response = res;
    throw err;
  }
  return res.data;
}

export default http;
